﻿#include "languagehandler.h"

#include <QDebug>
#include <QDir>
#include <QTranslator>
#include <QApplication>

namespace Common{

Language::Language(QString fileName, QString countryCode)
    : fileName(fileName)
    , selected(false)
{
    switchName(countryCode);
}

void Language::switchName(QString code)
{
    if(code.toLower() == QString("cn"))
    {
        name = QStringLiteral("简体中文");
    }
    else if(code.toLower() == QString("us"))
    {
        name = QStringLiteral("English");
    }
}

class LanguageHandlerPrivate
{
    Q_DECLARE_PUBLIC(LanguageHandler)
public:
    LanguageHandlerPrivate(LanguageHandler * q)
        :q_ptr(q)
    {

    }

    LanguageHandler * q_ptr;         //

    LanguagePtrList lanlist;        // 语言列表
    QString transPath;              // 保存翻译文件路径
    QTranslator translator;         // 翻译
};

LanguageHandler::LanguageHandler()
    : QObject()
    , d_ptr(new LanguageHandlerPrivate(this))
{

}

LanguageHandler::~LanguageHandler()
{

}

void LanguageHandler::loadTranslator(QString filePath)
{
    Q_D(LanguageHandler);

    QStringList nameFilters;
    nameFilters << QString("*.qm");

    QDir dir(filePath);
    QStringList qmfiles = dir.entryList(nameFilters);
    d->transPath = filePath;

    QLocale locale;

    std::for_each(qmfiles.begin(), qmfiles.end(), [&](const QString & fileName)
    {
        QStringList result = fileName.left(fileName.indexOf(".")).split("_");
        if(result.size() == 3)
        {
            Language * la = new Language(fileName,result.at(2));
            if(fileName.contains(locale.name()))
            {
                la->setSelected(true);
            }
            d->lanlist.push_back(la);
        }
    });
}

bool LanguageHandler::switchLanguage(QString fileName)
{
    Q_D(LanguageHandler);
    if(d->translator.load(fileName, d->transPath))
    {
        qApp->installTranslator(&d->translator);
        return true;
    }
    return false;
}

LanguagePtrList LanguageHandler::languages()
{
    Q_D(LanguageHandler);
    return d->lanlist;
}

Language *LanguageHandler::findLan(QString fileName)
{
    Q_D(LanguageHandler);
    for(int i = 0; i < d->lanlist.size();i++)
    {
        if(d->lanlist.at(i)->getFileName() == fileName)
        {
            return d->lanlist.at(i);
        }
    }
    return NULL;
}

} //namespace Base
